#include <header.h>
#include <stdio.h>
#include <time.h>
#include <string.h>

typedef struct usr{
    int usrfd;
    time_t last_time;
}usr;

//配置文件
int getparameter(char *key, char *value){
    FILE * file = fopen("config.ini", "r");
    while(1){
        char line[100];
        bzero(line, sizeof(line));
        char *res = fgets(line, sizeof(line), file);
        if(res == NULL){
            char buf[] = "没有要找的内容 \n";
            memcpy(value, buf, strlen(buf));
            return -1;
        }
        char *line_key = strtok(line, "=");
        if(strcmp(key, line_key) == 0){
            char *line_value = strtok(NULL, "=");
            memcpy(value, line_value, strlen(line_value));
            return 0;
        }
    }
    return 0;
}

//日志
typedef enum {
    LOG1_DEBUG,
    LOG1_INFO,
    LOG1_WARNING,
    LOG1_ERROR
} LogLevel;

void log_message(LogLevel level, const char *message);

#define LOG_LEVEL LOG1_INFO  // 可改为 LOG_DEBUG, LOG_ERROR 等

void log_debug(const char *msg) {
#if LOG_LEVEL <= LOG1_DEBUG
    log_message(LOG1_DEBUG, msg);
#endif
}

void log_info(const char *msg) {
#if LOG_LEVEL <= LOG1_INFO
    log_message(LOG1_INFO, msg);
#endif
}

void log_warning(const char *msg) {
#if LOG_LEVEL <= LOG1_WARNING
    log_message(LOG1_WARNING, msg);
#endif
}

void log_error(const char *msg) {
#if LOG_LEVEL <= LOG1_ERROR
    log_message(LOG1_ERROR, msg);
#endif
}


void log_message(LogLevel level, const char *message) {
    const char *level_str[] = {
        "DEBUG",
        "INFO",
        "WARNING",
        "ERROR"
    };

    FILE *fp = fopen("serve.log", "a");
    if (!fp) return;

    time_t now;
    time(&now);
    char *time_str = ctime(&now);
    time_str[strlen(time_str) - 1] = '\0';  // 去掉换行符

    fprintf(fp, "[%s] [%s] %s\n", time_str, level_str[level], message);
    fclose(fp);
}

int main()
{
    char ip[100];
    bzero(ip, sizeof(ip));
    getparameter("ip", ip);
    printf("ip is = %s", ip);
    char port[100];
    bzero(port, sizeof(port));
    getparameter("port", port);
    printf("port is = %s", port);
    log_info("get ip and port");

    int socket_fd=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in sock;
    sock.sin_family=AF_INET;
    sock.sin_port=htons(atoi(port));
    sock.sin_addr.s_addr=inet_addr(ip);
    size_t ret=bind(socket_fd,(struct sockaddr*)&sock,sizeof(sock));
    ERROR_CHECK(ret,-1,"bind");
    listen(socket_fd,10);

    fd_set set;
    FD_ZERO(&set);
    FD_SET(socket_fd,&set);
    usr list[100];
    memset(list,0,sizeof(list));
    int size=0;
    int count=0;
    int max=socket_fd;

    while(1){
        fd_set temp;
        memcpy(&temp,&set,sizeof(set));
        //超时剔除
        struct timeval tv;
        tv.tv_sec=1;
        tv.tv_usec=0;
        int num=select(max+1,&temp,NULL,NULL,&tv);
        if(num==0){
            for(int i=0;i<size;i++){
                time_t new_time;
                time(&new_time);
                if(new_time-list[i].last_time>30){
                    FD_CLR(list[i].usrfd,&set);
                    close(list[i].usrfd);
                    for(int k=i;k<size;k++){
                        list[k]=list[k+1];
                    }
                    size--;
                    i--;
                }
            }
        }
        //有新连接进来，分配一个socket
        if(FD_ISSET(socket_fd,&temp)){
            int net_fd=accept(socket_fd,NULL,NULL);
            list[size].usrfd=net_fd;
            time_t last_time;
            time(&last_time);
            list[size].last_time=last_time;
            size++;
            FD_SET(net_fd,&set);
            max=max>net_fd?max:net_fd;
        }
        //监听所有的socket对象，对发请求的socket进行处理
        for(int i=0;i<size;i++){
            int net_fd=list[i].usrfd;
            if(FD_ISSET(net_fd,&temp)){
                char buf[4096]={0};
                int ret=recv(net_fd,buf,sizeof(buf),0);
                if(ret==0){//ret为0，对方自动断开连接，进行处理
                    FD_CLR(net_fd,&set);
                    close(net_fd);
                    for(int k=i;k<size;k++) list[k]=list[k+1];
                    size--;
                    i--;
                    continue;        
                }
                else if(buf[0]=='P'||buf[1]=='O'){//对来自stm32端的报文进行处理
                    printf("post linked\n");
                    int fd=open("1.txt",O_RDWR);
                    lseek(fd, 0, SEEK_END);
                    ERROR_CHECK(fd,-1,"open");
                    char data[100]={0};
                    char str[4096]={0};
                    strcpy(str,buf);
                    char *p=strstr(str,"{\"");
                    printf("%s\n",p+2);
                    p=p+2;
                    for(int i=0;p[i]!='"';i++){
                        data[i]=p[i];
                    }
                    data[strlen(data)]='\n';
                    write(fd,data,strlen(data));
                    if(count<5){
                        count++;
                    }
                    char response[3]="OK";
                    send(net_fd,response,sizeof(response),0);
                    close(fd);
                }

                else{
                    printf("%s\n",buf);
                    char str[5][1000]={{0}};
                    printf("get linked\n");
                    if(count<5){
                        int fd=open("1.txt",O_RDWR);
                        ERROR_CHECK(fd,-1,"open");
                        int i=0;
                        char data[28]={0};
                        while(read(fd,data,sizeof(data))!=0&&i!=5){
                            data[strlen(data)]=0;
                            strcpy(str[i],data);
                            i++;
                        }
                        char ans[100]="waiting data";
                        for(;i<5;i++){
                            int j=0;
                            while(ans[j]!=0){
                                str[i][j]=ans[j];
                                j++;
                            }
                        }
                        close(fd);
                    }
                    else{
                        int fd=open("1.txt",O_RDWR);
                        ERROR_CHECK(fd,-1,"open");
                        lseek(fd,-140,SEEK_END);

                        int i=0;
                        while(1){
                            char data[28]={0};
                            size_t ret=read(fd,data,sizeof(data));
                            data[strlen(data)]=0;
                            printf("218:%s\n",data);
                            if(ret==0){
                                close(fd);
                                break;
                            }
                            strcpy(str[i],data);
                            i++;
                        }
                    }

                    char Str[4096];
                    sprintf(Str,"HTTP/1.1 200 OK\r\n\r\n[\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"]",str[0],str[1],str[2],str[3],str[4]);
                    for(int i=0;i<5;i++){
                        printf("--%s--\n",str[i]);
                    }
                    send(net_fd,Str,strlen(Str),0);
                    FD_CLR(list[i].usrfd,&set);
                    close(list[i].usrfd);
                    for(int k=i;k<size;k++){
                        list[k]=list[k+1];
                    }
                    size--;
                    i--;
                }
            }
        }
    }
    close(socket_fd);
    return 0;
}

